package com.college.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.college.eduService.entity.vo.OneSubject;
import com.college.eduService.entity.vo.TwoSubject;
import com.college.eduService.entity.excel.Subject;
import com.college.eduService.listener.SubjectExcelListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.college.eduService.entity.EduSubject;
import com.college.eduService.mapper.EduSubjectMapper;
import com.college.eduService.service.EduSubjectService;
import org.springframework.web.multipart.MultipartFile;

@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService{
    @Autowired
    EduSubjectMapper mapper;

    //通过EasyExcel的方法进行读取文件实现添加
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream in =file.getInputStream();
            //调用方法读取
            EasyExcel.read(in, Subject.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){

        }

    }

    //对一级分类和二级分类的数据进行封装
    @Override
    public List<OneSubject> getAll() {
        QueryWrapper<EduSubject> onewrapper=new QueryWrapper<>();
        onewrapper.eq("parent_id",0);
        //获取所有一级节点
        List<EduSubject> oneSubjects = mapper.selectList(onewrapper);
        // 查询所有二级分类
        QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<>();
        twoWrapper.ne("parent_id", "0");
        List<EduSubject> twoSubjectList = mapper.selectList(twoWrapper);

        // 存储最终结果
        List<OneSubject> result = new ArrayList<>();

        for (EduSubject eduSubject:oneSubjects){
            OneSubject oneSubject = new OneSubject();
            //将edusubject的属性赋值给onesubject（前提是属性一致）
            BeanUtils.copyProperties(eduSubject, oneSubject);
            result.add(oneSubject);

            // 封装二级分类
            List<TwoSubject> children = new ArrayList<>();
            for (EduSubject twoSubject:twoSubjectList){
                // 判断其父级 id 是否等于
                if (twoSubject.getParentId().equals(eduSubject.getId()) == true) {
                    TwoSubject tempTwoSubject = new TwoSubject();
                    BeanUtils.copyProperties(twoSubject, tempTwoSubject);
                    children.add(tempTwoSubject);
                }
            }
            oneSubject.setChildren(children);
        }
        return result;
    }
}
